package iamutkarshtiwari.github.io.ananas.editimage.fragment;

import iamutkarshtiwari.github.io.ananas.ResourceTable;
import iamutkarshtiwari.github.io.ananas.editimage.EditImageAbility;
import iamutkarshtiwari.github.io.ananas.editimage.fliter.PhotoProcessing;
import iamutkarshtiwari.github.io.ananas.editimage.utils.LoadingView;
import io.reactivex.Single;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

public class BeautyFragment extends ComponentContainer implements Slider.ValueChangedListener {   //关键jni功能的调用
    private PageSlider pageSlider;
    private Image back;
    private EditImageAbility editImageAbility;
    private Slider smoothValueBar, whiteValueBar;
    private int smooth = 0;
    private int whiteSkin = 0;
    private PixelMap finalBmp;

    private CompositeDisposable disposable = new CompositeDisposable();
    private Disposable beautyDisposable;
    private LoadingView loadingView;
    private Component roundProgress;

    EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());

    public BeautyFragment(Context context, PageSlider pageSlider) {
        super(context);
        this.pageSlider = pageSlider;
        this.editImageAbility = (EditImageAbility) context;
        initView();
        initDialog();
    }

    public BeautyFragment(Context context, AttrSet attrSet) {
        super(context, attrSet);
    }

    public BeautyFragment(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    /**
     * beauty主界面的初始化
     */
    private void initView() {
        Component component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_fragment_beauty_layout, null, false);
        addComponent(component);

        back = (Image) component.findComponentById(ResourceTable.Id_back_to_main);
        smoothValueBar = (Slider) component.findComponentById(ResourceTable.Id_smooth_value_bar);
        whiteValueBar = (Slider) component.findComponentById(ResourceTable.Id_white_skin_value_bar);

        smoothValueBar.setValueChangedListener(this);
        whiteValueBar.setValueChangedListener(this);

        back.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                backToMain();
            }
        });
    }


    private void initDialog() {
        Component component = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_view_loading, null, true);
        roundProgress = component.findComponentById(ResourceTable.Id_roundprogressbar);
        loadingView = LoadingView.decorate(getContext(), component)
                .setSize(900, 230)
                .build();
    }

    /**
     * 移动seekbar后的效果展示，效果展示耗时，有点延迟
     *
     * @param slider   Slider
     * @param position int
     * @param flag     boolean
     */
    @Override
    public void onProgressUpdated(Slider slider, int position, boolean flag) {
        doBeautyTask();
    }

    @Override
    public void onTouchStart(Slider slider) {
//        loadingView.show(roundProgress);
    }

    @Override
    public void onTouchEnd(Slider slider) {

        loadingView.show(roundProgress);
        eventHandler.postTask(() -> loadingView.hide(), 100);
    }

    protected void doBeautyTask() {
        if (beautyDisposable != null && !beautyDisposable.isDisposed()) {
            beautyDisposable.dispose();
        }
        smooth = smoothValueBar.getProgress();
        whiteSkin = whiteValueBar.getProgress();

        if (smooth == 0 && whiteSkin == 0) {
            editImageAbility.mainImage.setPixelMap(editImageAbility.getMainBit());//setImageBitmap
            return;
        }

        beautyDisposable = beautify(smooth, whiteSkin)
//                .subscribeOn(Schedulers.computation())
//                .observeOn(Schedulers.mainThread())
//                .doOnSubscribe(subscriber -> dialog.show())
//                .doFinally(() -> dialog.dismiss())
                .subscribe(bitmap -> {
                    if (bitmap == null)
                        return;
                    editImageAbility.mainImage.setPixelMap(bitmap);
                    finalBmp = bitmap;
                }, e -> {
                    // Do nothing on error
                });
        disposable.add(beautyDisposable);
    }

    private Single<PixelMap> beautify(int smoothVal, int whiteSkinVal) {
        return Single.fromCallable(() -> {
//            Bitmap srcBitmap = Bitmap.createBitmap(
//                    editImageAbility.getMainBit().copy(Bitmap.Config.ARGB_8888, true));
            PixelMap.InitializationOptions opts = new PixelMap.InitializationOptions();
            opts.pixelFormat = PixelFormat.ARGB_8888;
            opts.editable = true;

            PixelMap srcBitmap = PixelMap.create(editImageAbility.getMainBit(), opts);
            PhotoProcessing.handleSmoothAndWhiteSkin(srcBitmap, smoothVal, whiteSkinVal);
            return srcBitmap;
        });
    }

    /**
     * 返回主界面
     */
    public void backToMain() {
        this.smooth = 0;
        this.whiteSkin = 0;
        smoothValueBar.setProgressValue(0);
        whiteValueBar.setProgressValue(0);

        editImageAbility.mode = EditImageAbility.MODE_NONE;
        editImageAbility.mainImage.setPixelMap(editImageAbility.getMainBit());// 返回原图
//        editImageAbility.bottomGallery.setCurrentItem(MainMenuFragment.INDEX);
//        editImageAbility.mainImage.setVisibility(View.VISIBLE);
//        editImageAbility.bannerFlipper.showPrevious();
        pageSlider.setCurrentPage(0, false);
        pageSlider.setVisibility(Component.HIDE);
        onDestroy();
        editImageAbility.saveOrApply(false);
    }

    /**
     * 切换到Beauty界面，显示需要的控件
     */
    public void onShow() {
        editImageAbility.mode = EditImageAbility.MODE_BEAUTY;
        editImageAbility.mainImage.setPixelMap(editImageAbility.getMainBit());
    }

    /**
     * Beauty修改后的效果应用
     */
    public void applyBeauty() {
        if (finalBmp != null && (smooth != 0 || whiteSkin != 0)) {
            editImageAbility.changeMainBitmap(finalBmp, true);
        }

        backToMain();
    }

    //    @Override
    public void onDestroy() {
//        super.onDestroy();
        disposable.dispose();
    }


}
